package rsasha1

import (
	"crypto"
	"crypto/rsa"
	"crypto/sha256"
	"crypto/x509"
	"encoding/base64"
	"encoding/pem"
	"fmt"

	"gitlab.maoka-inc.com/maoka/maoka-base/sign"
)

type RSASHA256 struct{}

//生成签名 签名内容 私钥
func (*RSASHA256) Sign(content []byte, key []byte) (string, error) {
	p, _ := pem.Decode(key)
	if p == nil {
		return "", fmt.Errorf("no pem block found")
	}
	privateKey, err := x509.ParsePKCS1PrivateKey(p.Bytes)
	if err != nil {
		return "", err
	}

	h := sha256.New()
	h.Write(content)
	sum := h.Sum(nil)
	sign, err := rsa.SignPKCS1v15(nil, privateKey, crypto.SHA256, sum)
	return base64.StdEncoding.EncodeToString(sign), err
}

//验签数据 签名内容 公钥 签名
func (*RSASHA256) Verify(content []byte, key []byte, sign string) error {
	p, _ := pem.Decode(key)
	if p == nil {
		return fmt.Errorf("no pem block found")
	}
	publicKey, err := x509.ParsePKCS1PublicKey(p.Bytes)
	if err != nil {
		return err
	}
	s, err := base64.StdEncoding.DecodeString(sign)
	if err != nil {
		return err
	}

	h := sha256.New()
	h.Write([]byte(content))
	sum := h.Sum(nil)
	return rsa.VerifyPKCS1v15(publicKey, crypto.SHA256, sum, s)
}

func init() {
	sign.RegisterSignObject("rsasha256", &RSASHA256{})
}
